package com.orjl.networkj;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 版权： 版权所有
 * <p>
 * 作者：suntinghui
 * <p>
 * 创建日期：2018/11/21 0021 11:24
 * <p>
 * 描述：
 * <p>
 * 修订历史：
 */
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
//        String E = "";
//        try {
//            E = AESUtil.encrypt(value.string());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String cipherText = "";
//
//
//        String D = "";
//        JSONObject jsonObject = null;
//        try {
//            jsonObject= new JSONObject(value.string());
//            cipherText = jsonObject.getString("data");
//
//            D = AESUtil.decrypt(cipherText);
//        } catch (Exception e) {
//            D = jsonObject.toString();
//            e.printStackTrace();
//
//        }


        int code = -1;
        String msg = "";
        JSONObject jsonResponse = null;
        try {
            jsonResponse = new JSONObject(value.string().toString());
            code = jsonResponse.getInt("code");
            msg = jsonResponse.getString("msg");
            if (code != 200) {
                try {
                    return (T) new BaseResponseObjectModel(code, msg, null);
                } finally {
                    value.close();
                }
            }


        } catch (JSONException e) {
            e.printStackTrace();
            try {
                return (T) new BaseResponseObjectModel(-1, "返回数据不是一个json格式", null);
            } finally {
                value.close();
            }
        }


        Reader reader = new StringReader(jsonResponse.toString());


        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } finally {
            value.close();
        }
    }
}
